package etcd

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"go.etcd.io/etcd/clientv3"
)
var cli *clientv3.Client

type LogEntry struct{
	Path string `json:"path"`
	Topic string `json:"topic"`
}
func Init(address string,timeout time.Duration) (err error){
	cli,err=clientv3.New(clientv3.Config{
		Endpoints:[]string{"127.0.0.1:2379"},
		DialTimeout:timeout,
	})
	if err!=nil {
		fmt.Println("connect to etcd failed", err)
		return
	}
	return
}

func GetConf(key string) (LogEntries []*LogEntry,err error){
	ctx,cancel:=context.WithTimeout(context.Background(),time.Second)
	resp,err:=cli.Get(ctx,key)
	cancel()
	if err!=nil{
		fmt.Println("get from etcd failed",err)
		return
	}
	//path=c:/tmp/nginx topic=nginx_log
	for _,ev:=range resp.Kvs{
		err=json.Unmarshal(ev.Value,&LogEntries)
		if err!=nil{
			fmt.Println("Unmarshal err",err)
			return nil,err
		}
	}
	return
}

//监听日志项的变化
func WatchConf(key string,newconfch chan<- []*LogEntry){
	rch:=cli.Watch(context.Background(),key)
	for wresp:=range rch{
		for _,ev:=range wresp.Events{
			fmt.Printf("Type:%s Key:%s Value:%s\n",ev.Type,ev.Kv.Key,ev.Kv.Value)
			//拿到变化之后，就要通知taillog模块，采用管道的形式
			var newconf []*LogEntry
			if ev.Type!=clientv3.EventTypeDelete{
				err:=json.Unmarshal(ev.Kv.Value,&newconf)
				if err!=nil{
					fmt.Println("反序列化日志失败",err)
					return
				}
			}
			fmt.Println("获取到新的配置",newconf)
			newconfch<-newconf
		}
	}
}